package com.example.dell.controllsmall.activity.control;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.os.SystemClock;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.dell.controllsmall.activity.R;
import com.example.dell.controllsmall.activity.activity.MainActivity;
import com.example.dell.controllsmall.activity.base.ControlBaseActivity;
import com.example.dell.controllsmall.activity.config.Constants;
import com.example.dell.controllsmall.activity.custom.AnimationView;
import com.example.dell.controllsmall.activity.dao.DataBaseDao;
import com.example.dell.controllsmall.activity.dao.LocalInfo;
import com.example.dell.controllsmall.activity.dao.UserInfo;
import com.example.dell.controllsmall.activity.db.UserInfoDao;
import com.example.dell.controllsmall.activity.db.manager.UserInfoDbManager;
import com.example.dell.controllsmall.activity.login.SingleLogin;
import com.example.dell.controllsmall.activity.service.UDPAcceptReceiver;
import com.example.dell.controllsmall.activity.service.UdpService;
import com.example.dell.controllsmall.activity.util.BitmapUtils;
import com.example.dell.controllsmall.activity.util.ExtUtil;
import com.example.dell.controllsmall.activity.util.FileUtil;
import com.example.dell.controllsmall.activity.util.GsonUtil;
import com.example.dell.controllsmall.activity.util.PhoneUtil;
import com.example.dell.controllsmall.activity.util.PreferencesUtils;
import com.example.dell.controllsmall.activity.util.ReceiveMessage;
import com.example.dell.controllsmall.activity.util.SendToRobot;
import com.ocean.mvp.library.utils.L;
import com.yuntongxun.ecsdk.ECChatManager;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.ECVoIPCallManager;
import com.yuntongxun.ecsdk.ECVoIPSetupManager;
import com.yuntongxun.ecsdk.Parameters;
import com.yuntongxun.ecsdk.PersonInfo;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.ecsdk.im.ECFileMessageBody;
import com.yuntongxun.ecsdk.im.ECTextMessageBody;
import com.yuntongxun.ecsdk.im.ECVoiceMessageBody;
import com.yuntongxun.ecsdk.voip.video.ECCaptureView;
import com.yuntongxun.ecsdk.voip.video.ECOpenGlView;
import com.yuntongxun.ecsdk.voip.video.OnCameraInitListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.example.dell.controllsmall.activity.util.Md5Util;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Call;


/**
 * Created by zhangyuanyuan on 2017/7/8.
 */

public class ControlView extends ControlBaseActivity<ControlPresenter> implements IControlView, View.OnClickListener, UDPAcceptReceiver.UDPAcceptInterface, ReceiveMessage, ECChatManager.OnDownloadMessageListener {
    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public ControlPresenter createPresenter() {
        return new ControlPresenter(this);
    }

    @Override
    protected int getContentViewResource() {
        return R.layout.activity_control;
    }

    private Button mCancelVideo, mAcceptVideo, mReleaseVideo;
    private EditText mEditText;
    private NavController navController;

    private TextView mConnetState, mSendEdit;
    private ImageView mChangeTxtOrVoice, mControlSetting, mSport, mVoice, mLike, mLink, mRrelink, mOpenSurface, mLocalView,
            mHideInput, mRepeat, mVoicePeople, mGroup;
    private Button mAsrBtn;
    private LinearLayout mEditLayout, mReleaseLayout, mAcceptLayout;
    private RelativeLayout mControlRelative, mMessage, mEdit;

    private TextView mQuestion, mAnswer, mTip;

    //  private NavController navController;

    private LinearLayout mAnimationLayout;

    private AnimationView mVoiceView;

    private FrameLayout mGlView_frameLayout;

    /**
     * 当前呼叫类型对应的布局
     */
    FrameLayout mCallRoot;

    private ECOpenGlView mRemoteVideoView, mLocalVideoView;

    private ECCaptureView mCaptureView;
    //计时器
    private Chronometer mChronometer;

    private LocalBroadcastManager mLbmManager;
    private boolean isAccept;
    //udp
    private UDPAcceptReceiver mUdpAcceptReceiver;

    private SendToRobot sendToRobot;
    private DataBaseDao dataBaseDao;

    @Override
    protected void onViewInit() {
        super.onViewInit();
        mSendEdit = (TextView) findViewById(R.id.send_text);
        mEditText = (EditText) findViewById(R.id.edit_text);
        navController = (NavController) findViewById(R.id.nav_control);
        navController.setOnNavAndSpeedListener(mPresenter);
        mConnetState = (TextView) findViewById(R.id.connect_state);
        mChangeTxtOrVoice = (ImageView) findViewById(R.id.change_text_voice);
        mAsrBtn = (Button) findViewById(R.id.voice_btn);
        mEditLayout = (LinearLayout) findViewById(R.id.edit_text_layout);


        mRrelink = (ImageView) findViewById(R.id.relink_imageView);
        mAnimationLayout = (LinearLayout) findViewById(R.id.voice_animation_bg);
        mVoiceView = (AnimationView) findViewById(R.id.voice_animation);
        (mLocalView) = (ImageView) findViewById(R.id.localView_imageView);
        (mGroup) = (ImageView) findViewById(R.id.iv_group);

        (mCallRoot) = (FrameLayout) findViewById(R.id.callRoot_fm);
        (mCancelVideo) = (Button) findViewById(R.id.btn_cancel_video);
        (mAcceptVideo) = (Button) findViewById(R.id.video_btn_accept);
        (mReleaseVideo) = (Button) findViewById(R.id.video_btn_relese);

        (mGlView_frameLayout) = (FrameLayout) findViewById(R.id.glView_frameLayout);
        (mReleaseLayout) = (LinearLayout) findViewById(R.id.ll_release);
        (mAcceptLayout) = (LinearLayout) findViewById(R.id.ll_begin);
        (mTip) = (TextView) findViewById(R.id.tv_tip);
        (mChronometer) = (Chronometer) findViewById(R.id.chronometer);
        mChronometer.stop();
        mChronometer.setVisibility(View.GONE);

        (mRemoteVideoView) = (ECOpenGlView) findViewById(R.id.remote_video_view);
        mRemoteVideoView.setGlType(ECOpenGlView.RenderType.RENDER_REMOTE);
        mRemoteVideoView.setAspectMode(ECOpenGlView.AspectMode.CROP);

        (mOpenSurface) = (ImageView) findViewById(R.id.openSurface_imageView);

        (mLocalVideoView) = (ECOpenGlView) findViewById(R.id.local_video_view);
        mLocalVideoView.setGlType(ECOpenGlView.RenderType.RENDER_PREVIEW);
        mLocalVideoView.setAspectMode(ECOpenGlView.AspectMode.CROP);

        (mLike) = (ImageView) findViewById(R.id.like_imageView);
        (mControlSetting) = (ImageView) findViewById(R.id.controlSetting_imageView);
        (mSport) = (ImageView) findViewById(R.id.sport_imageView);
        (mVoice) = (ImageView) findViewById(R.id.voice_imageView);
//        (mSetting) = (ImageView) findViewById(R.id.setting_imageView);
        mControlRelative = (RelativeLayout) findViewById(R.id.control_relative);

        (mLink) = (ImageView) findViewById(R.id.link_imageView);

        (mMessage) = (RelativeLayout) findViewById(R.id.message_relative);
        (mEdit) = (RelativeLayout) findViewById(R.id.edit_layout);
        (mHideInput) = (ImageView) findViewById(R.id.hideInput_iv);
        (mRepeat) = (ImageView) findViewById(R.id.repeat_imageView);

        (mVoicePeople) = (ImageView) findViewById(R.id.voicePeople_imageview);

        mPresenter.attachGlView(mLocalVideoView, mRemoteVideoView);
        SingleLogin.getInstance(this, "").setReceive(this);

        mCaptureView = new ECCaptureView(this);
        dataBaseDao = new DataBaseDao(this);
        setCaptureView(mCaptureView);
        Constants.IP = PhoneUtil.getWifiIP(this);

        sendToRobot = new SendToRobot();
        mLbmManager = LocalBroadcastManager.getInstance(this);
        sendToRobot.SendRobot(Constants.IP, "IP");
        //发送自己的ip

        //像机器人发送自己当前 版本
        int currentVersion = PreferencesUtils.getInt(this, "LocalVoice", -1);
        sendToRobot.SendRobot(String.valueOf(currentVersion), "version");

    }


    @Override
    protected void setOnListener() {
        super.setOnListener();
        mRrelink.setOnClickListener(this);
        mSendEdit.setOnClickListener(this);
        mChangeTxtOrVoice.setOnClickListener(this);
        mAsrBtn.setOnClickListener(this);
        //   navController.setOnNavAndSpeedListener(mPresenter);
        mLocalVideoView.setOnClickListener(this);
        mCancelVideo.setOnClickListener(this);
        mAcceptVideo.setOnClickListener(this);
        mReleaseVideo.setOnClickListener(this);
        mOpenSurface.setOnClickListener(this);
        mLike.setOnClickListener(this);
        mControlSetting.setOnClickListener(this);
        mSport.setOnClickListener(this);
        mVoice.setOnClickListener(this);
//        mSetting.setOnClickListener(this);
        mMessage.setOnClickListener(this);
        mHideInput.setOnClickListener(this);
        mRepeat.setOnClickListener(this);
        mVoicePeople.setOnClickListener(this);
        mGroup.setOnClickListener(this);
        mCaptureView.setOnCameraInitListener(new OnCameraInitListener() {
            @Override
            public void onCameraInit(boolean result) {
                if (!result) L.e("key", "摄像头被占用");
            }
        });
        //本地视频view点击事件
        mLocalVideoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
//        mEditText.setOnKeyListener(onKeyListener);
    }


    @Override
    protected void onResume() {
        super.onResume();
        isAccept = true;
        mUdpAcceptReceiver = new UDPAcceptReceiver(this);
        IntentFilter intentFilter = new IntentFilter(Constants.UDP_ACCEPT_ACTION);
        mLbmManager.registerReceiver(mUdpAcceptReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isAccept = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLbmManager.unregisterReceiver(mUdpAcceptReceiver);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //自由运动
            case R.id.sport_imageView:
                mPresenter.sendAutoAction();
                break;
            //
//            case R.id.setting_imageView:
//                mPresenter.showInterfaceDialog();
//                break;
            //语音开关
            case R.id.voice_imageView:
                mPresenter.sendSpeech();
                break;
            //
            case R.id.like_imageView:
                mPresenter.showSceneDialog();
                break;
            case R.id.send_text:
//                mPresenter.sendText();//暂时先关掉
                mPresenter.sendAIUIText();
                break;
            case R.id.change_text_voice:
                mPresenter.changeSpeech();
                break;
            //复读
            case R.id.repeat_imageView:
                mPresenter.doRepear();
                break;
//            case R.id.asr_send:
//                mPresenter.sendAsrResult();
//                break;
            case R.id.relink_imageView:
                mPresenter.reLink();
                break;
            case R.id.voice_btn:
                mPresenter.audioPermission();
                break;
            case R.id.localView_imageView:
                mPresenter.localViewVisible();
                break;
            case R.id.btn_cancel_video:
                mPresenter.onRefuse();
                break;
            case R.id.video_btn_accept:
                mPresenter.attachGlView(mLocalVideoView, mRemoteVideoView);
                mPresenter.onAccept();
                break;
            case R.id.video_btn_relese:
                mPresenter.onHangUp();
                break;
            //视频通话
            case R.id.openSurface_imageView:
                mPresenter.makeCall(ECVoIPCallManager.CallType.VIDEO);
                break;
            case R.id.controlSetting_imageView:
                mPresenter.showControl(mControlRelative);
                break;
            case R.id.message_relative:
                mPresenter.showInput(mEdit);
                break;
            case R.id.hideInput_iv:
                mPresenter.showInput(mEdit);
                break;
            // 区别语言
            case R.id.voicePeople_imageview:
                mPresenter.showPersonSelectDialog();
                break;
            //群组发消息
            case R.id.iv_group:
                mPresenter.createGroup();
                break;
            default:
                break;
        }
    }

    @Override
    public String getEditText() {
        return mEditText.getText().toString();
    }

    @Override
    public void setEditText(String text) {
        mEditText.setText(text);
    }


    @Override
    public void setTextView(String textView) {
        mConnetState.setText(textView);
    }

    @Override
    public void setLayoutVisible(boolean visible) {
        if (visible) {
            mEditLayout.setVisibility(View.VISIBLE);
            mAsrBtn.setVisibility(View.INVISIBLE);
//            mAsrResultLayout.setVisibility(View.GONE);
            mChangeTxtOrVoice.setImageResource(R.mipmap.ic_input_voice);

        } else {
            mEditLayout.setVisibility(View.GONE);
            mAsrBtn.setVisibility(View.VISIBLE);
            mChangeTxtOrVoice.setImageResource(R.mipmap.ic_input);
        }
    }

    @Override
    public void setAsrLayoutVisible(boolean visible) {
//        mAsrResultLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setQuestion(String question) {
        mQuestion.setText(question);
    }

    @Override
    public void setAnswer(String answer) {
        mAnswer.setText(answer);
    }

    @Override
    public AnimationView getVoiceView() {
        return mVoiceView;
    }

    @Override
    public void setAnimationVisible(boolean visible) {
        mAnimationLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setLocalViewVisiable(boolean viewVisiable) {
        mLocalVideoView.setVisibility(viewVisiable ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setBottomVisible(boolean visible) {
        mReleaseLayout.setVisibility(visible ? View.GONE : View.VISIBLE);//结束(呼出)
        mAcceptLayout.setVisibility(visible ? View.VISIBLE : View.GONE);//接收(呼入)
    }

    @Override
    public void setTopText(String text) {
        mTip.setText(text);
    }

    @Override
    public void startUpChronometer(boolean falg) {
        if (falg) {
            mChronometer.start();
        } else {
            mChronometer.stop();
        }
    }

    @Override
    public void setChronometerVisible(boolean visible) {
        mChronometer.setVisibility(visible ? View.VISIBLE : View.GONE);
    }


    @Override
    public void setChronometerTime() {
        mChronometer.setBase(SystemClock.elapsedRealtime());
    }


    @Override
    public void setGlViewVisable(boolean visable) {
        mGlView_frameLayout.setVisibility(visable ? View.VISIBLE : View.GONE);
    }


    @Override
    public void setSportVisiable(boolean visiable) {
        if (visiable) {
            mSport.setImageResource(R.mipmap.ic_control_sport);
        } else {
            mSport.setImageResource(R.mipmap.ic_control_sport_pressed);
        }
    }

    @Override
    public void setVoicetVisiable(boolean visiable) {
        if (visiable) {
            mVoice.setImageResource(R.mipmap.ic_control_voice_pressed);
        } else {
            mVoice.setImageResource(R.mipmap.ic_control_voice);
        }
    }

    @Override
    public void setLinkVisiable(boolean visiable) {
        if (visiable) {
            mLink.setImageResource(R.mipmap.ic_control_link);
        } else {
            mLink.setImageResource(R.mipmap.ic_control_link_no);
        }
    }

    @Override
    public void setInputVisiable(boolean visiable) {

        mMessage.setVisibility(visiable ? View.GONE : View.VISIBLE);
        mEdit.setVisibility(visiable ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setRefuseVisable(boolean visable) {

        mReleaseLayout.setVisibility(visable ? View.GONE : View.VISIBLE);//结束(呼出)
    }

    @Override
    public void setRepeatShow(boolean isShow) {
        if (isShow) {
            mRepeat.setImageResource(R.mipmap.ic_repeat_pressed);
        } else {
            mRepeat.setImageResource(R.mipmap.ic_repeat);
        }
    }

    @Override
    public void setVoiceText(String text) {
        mAsrBtn.setText(text);
    }

    @Override
    public void setVoiceBack(boolean isClick) {
        if (isClick) {
            mAsrBtn.setBackgroundResource(R.mipmap.ic_voice_hangup);
        } else {
            mAsrBtn.setBackgroundResource(R.mipmap.ic_voice_bg);
        }
    }

    @Override
    public void sendToRobot(String order) {
        Intent intent = new Intent(Constants.UDP_SEND_ACTION);
        intent.putExtra("controlSend", order);
        mLbmManager.sendBroadcast(intent);
    }

    @Override
    public void setGrouping(boolean visiable) {
        mGroup.setImageResource(visiable ? R.mipmap.ic_group_pressed : R.mipmap.ic_group);
    }

    /**
     * 添加预览到视频通话界面上
     *
     * @param captureView 预览界面
     */
    private void addCaptureView(ECCaptureView captureView) {
        if (mCallRoot != null && captureView != null) {
            mCallRoot.removeView(mCaptureView);
            mCaptureView = null;
            mCaptureView = captureView;
            mCallRoot.addView(captureView, new RelativeLayout.LayoutParams(1, 1));
            mCaptureView.setVisibility(View.VISIBLE);
        }
    }


    public void setCaptureView(ECCaptureView captureView) {
        ECVoIPSetupManager setUpMgr = ECDevice.getECVoIPSetupManager();
        if (setUpMgr != null) {
            setUpMgr.setCaptureView(captureView);
        }
        addCaptureView(captureView);
    }

    @Override
    public void UDPAcceptMessage(String content) {
        if (isAccept) {
            showToast(content);
        }
    }


    @Override
    public void OnReceivedMessage(ECMessage msg) {
        if (msg.getUserData().equals("localVoiceFile")) {// 获取语音文件
            if (msg.getType() == ECMessage.Type.FILE) {
                ECChatManager ecChatManager = ECDevice.getECChatManager();
                ECFileMessageBody stateBody = (ECFileMessageBody) msg.getBody();
                File file = new File(BitmapUtils.projectPath + "localVoice.txt");
                if (file.exists()) {
                    stateBody.setLocalUrl(BitmapUtils.projectPath + "localVoice.txt");
                    msg.setBody(stateBody);
                    ecChatManager.downloadMediaMessage(msg, this);
                }
            }


        } else if (msg.getUserData().equals("version")) {// 判断版本
            ECTextMessageBody stateBody = (ECTextMessageBody) msg.getBody();
            int localVersion = Integer.valueOf(stateBody.getMessage());
            PreferencesUtils.putInt(this, "LocalVoice", localVersion);
        } else {
            ECTextMessageBody stateBody = (ECTextMessageBody) msg.getBody();
            String motion = stateBody.getMessage();
            Log.i("WWDZ", "ECMessag" + motion);
            try {
//            String order = bean.getOrder();

                JSONObject object = new JSONObject(motion);
                Constants.CONNECT_IP = object.getString("robotIp");
                Constants.CONNECT_PORT = object.getInt("robotPort");

                if (Constants.CONNECT_IP == null) {
                    throw new RuntimeException("connect ip null");
                }
                Intent intent = new Intent(this, UdpService.class);
                startService(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onDownloadMessageComplete(ECError ecError, ECMessage ecMessage) {
        if (ecError.errorCode == SdkErrorCode.REQUEST_SUCCESS) {
            if (ecMessage == null)
                return;
            String content = FileUtil.read(ControlView.this, BitmapUtils.projectPath + "localVoice.txt");
            List<UserInfo> userInfos = GsonUtil.GsonToArrayList(content, UserInfo.class);
            if (userInfos != null && userInfos.size() > 0) {
                UserInfoDbManager userInfoDbManager = new UserInfoDbManager();
                userInfoDbManager.deleteAll();
                userInfoDbManager.insertList(userInfos);
            }

        }
        Log.e("GG", "GG" + ecError.errorCode);
    }

    @Override
    public void onProgress(String s, int i, int i1) {
        Log.e("progress", "" + s);

    }
}
